from . import web
from app.forms.auth import RegisterForm, LoginForm, EmailForm, ResetPasswordForm
from flask import request, jsonify
from flask_login import login_user, logout_user

from app.models.user import User
from app.models.base import db


@web.route('/register', methods=['GET', 'POST'])
def register():
    form = RegisterForm(request.form)
    if request.method == 'POST' and form.validate():
        # 这里需要在基类上创建方法来进行赋值，不要一个个的写
        with db.auto_commit():
            user = User()
            user.set_attrs(form.data)
            db.session.add(user)
        return jsonify({'message': '注册成功'})
    else:
        return jsonify(form.errors)


@web.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm(request.form)
    if request.method == 'POST' and form.validate():
        user = User.query.filter_by(email=form.email.data).first()
        if user and user.check_password(form.password.data):
            # 用户验证成功 保存票据
            login_user(user, remember=True)
            return jsonify({'message': '登录成功'})
        else:
            return jsonify({'message': '账号或密码错误'})


@web.route('/reset/password', methods=['GET', 'POST'])
def forget_password_request():
    form = EmailForm(request.form)
    if request.method == 'POST':
        if form.validate():
            account_email = form.email.data
            user = User.query.filter_by(email=account_email).first_or_404()
            from app.libs.email import send_mail
            send_mail(form.email.data, '重置你的密码',
                      '/reset_password.html', user=user,
                      token=user.geneate_token())
            # if user:
            #     pass
            # pass
    return jsonify({'msg': '充值密码邮件发送成功！'})

@web.route('/reset/password/<token>', methods=['GET', 'POST'])
def forget_password(token):
    form = ResetPasswordForm(request.form)
    if request.method == 'POST' and form.validate():
        success = User.reset_password(token, form.password1.data)
        if success:
            return jsonify({'msg': '用户密码已更新，请使用新的密码登录'})
        else:
            return jsonify({'msg': '密码更新失败'})

@web.route('/logout')
def logout():
    logout_user()
    return jsonify({'msg': '用户退出成功'})
